package com.imstlife.vending.utils;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import com.imstlife.vending.vo.DrinkInfo;

import java.lang.reflect.Type;

/**
 * Created by lihaifeng on 16/11/2.
 */
public class GsonUtil {

    private static  GsonUtil ins;
    private static Gson gson = new Gson();

    public static GsonUtil getInstace(){

        if(ins==null){
            ins = new GsonUtil();
        }
        return ins;
    }




    public GsonUtil() {
        gson = new Gson();
    }

    public  DrinkInfo decodeMsgToDrinkInfo(String msg){
        return gson.fromJson(msg,DrinkInfo.class);
    }

    /**
     * 将对象准换为json字符串
     *
     * @param object
     * @param <T>
     * @return
     */
    public static <T> String serialize(T object) {
        return gson.toJson(object);
    }

    /**
     * 将json字符串转换为对象
     *
     * @param json
     * @param clz
     * @param <T>
     * @return
     */
    public static <T> T deserialize(String json, Class<T> clz) throws JsonSyntaxException {
        return gson.fromJson(json, clz);
    }

    /**
     * 将json对象转换为实体对象
     *
     * @param json
     * @param clz
     * @param <T>
     * @return
     * @throws JsonSyntaxException
     */
    public static <T> T deserialize(JsonObject json, Class<T> clz) throws JsonSyntaxException {
        return gson.fromJson(json, clz);
    }

    /**
     * 将json字符串转换为对象
     *
     * @param json
     * @param type
     * @param <T>
     * @return
     */
    public static <T> T deserialize(String json, Type type) throws JsonSyntaxException {
        return gson.fromJson(json, type);
    }

}
